package com.schooldate.base;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.openFire.Service.UserService;
import com.openFire.util.Blowfish;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import com.schooldate.model.entity.*;
import com.schooldate.model.service.*;
import com.schooldate.util.CommomUtils;
import net.sf.json.JsonConfig;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.dispatcher.multipart.JakartaMultiPartRequest;
import org.apache.struts2.interceptor.SessionAware;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;

import javax.mail.internet.MimeMessage;
import javax.servlet.ServletResponse;
import java.io.*;
import java.lang.reflect.ParameterizedType;
import java.util.*;

/**
 * Created by etund on 2015/3/12 0012.
 */
@SuppressWarnings("all")
public abstract class BaseAction<T> extends ActionSupport implements ModelDriven<T>,SessionAware {

    /**
     * 消息推送
     */
    protected List<String> devicetokens = new ArrayList<String>();
    protected String devicetoken = null;
    protected String content = null;



    /**
     * 文件上传
     */
    //   上传的文件
    protected File[] file;
    //    文件名称
    protected String[] fileFileName;
    //    文件类型
    protected String[] fileContentType;
    protected List<String> realPaths = new ArrayList<String>();
//    上传的是offic文档时
    protected String documentName;
    protected  String fileFullPath = null;



    protected String realPath;

    protected List<T> list = new ArrayList<T>();

    /**
     * 分页数据
     */
    protected Integer pageNo = 1;
    protected Integer totalCount = 0;
    protected Integer pageSize = 3;

    /**
     * entity类的集合
     */
    protected List<School> schools;
    protected List<Department> departments;
    protected List<UserInfo> userInfos;
    protected List<HandMessage> handMessages;
    protected List<MessageBoard> messageBoards;
    protected List<ADClass> ads;
    protected List<MessageBoardReply> messageBoardReplies;
    protected List<ExamSource> examSources;
    /**
     * service类
     */
    @Autowired
    protected SchoolService schoolService;
    @Autowired
    protected DepartmentService departmentService;
    @Autowired
    protected UserInfoService userInfoService;
    @Autowired
    protected HandMessageService handMessageService;
    @Autowired
    protected MessageBoardService messageBoardService;
    @Autowired
    protected ADClassService adservice;
    @Autowired
    protected MessageBoardReplyService messageBoardReplyService;
    @Autowired
    protected PraiseRecordService praiseRecordService;
    @Autowired
    protected ExamSourceService examSourceService;

    /**
     * openFireService类
     */
    @Autowired
    protected UserService userService;

    /**
     * 公共字段
     */
    protected String result;
    protected JSONObject object = new JSONObject();
    protected JsonConfig jsonConfig = new JsonConfig();
    protected String refreshNum;

    /**
     * openFire加密
     */
    protected  static Blowfish _encoder = new Blowfish("JCy8wOfxuR0jT1B");


    //    邮箱
    @Autowired
    protected JavaMailSenderImpl mailSender;


    protected  Map<String ,Object> session;
    protected   T model;
    public BaseAction() {
        try {
            ParameterizedType pt = (ParameterizedType)this.getClass().getGenericSuperclass();
            Class<T> clazz = (Class<T>)pt.getActualTypeArguments()[0];
            model = clazz.newInstance();
        }catch (Exception e){
            throw new RuntimeException(e);
        }
    }

    protected void uploadFileReturnPath(String floder) throws Exception{
        realPath = ServletActionContext.getServletContext().getRealPath("/"+floder);
        String tmpRealPath = null;
        for (int i = 0;i<file.length;i++) {
            tmpRealPath = null;
            String tmpFileName = fileFileName[i];
            File tmpFile = file[i];
            tmpRealPath = CommomUtils.createDirByHash(tmpFileName, realPath);
            realPaths.add(tmpRealPath);
            if (file != null) {
                File saveFile = new File(new File(tmpRealPath), tmpFileName);
                if (!saveFile.getParentFile().exists())
                    saveFile.getParentFile().mkdirs();
                FileUtils.copyFile(tmpFile, saveFile);
            }
        }
            for (int i = 0;i<file.length;i++) {
                String tmpFileName = fileFileName[i];
                System.out.println(tmpFileName+"===================="+i);
                if (!"".equals(tmpFileName.trim())) {
                    String[] strTmp = realPaths.get(i).split(floder);
                    String tmp = "/" + floder + strTmp[1] + "/" + tmpFileName;
                    if (fileFullPath==null){
                        fileFullPath = tmp;
                        continue;
                    }
                    fileFullPath = fileFullPath + ","+tmp;
                }
        }
        return;
    }


    /**
     * 文件上传
     * @throws Exception
     */
    protected void uploadImage(String path) throws Exception{
        realPath = ServletActionContext.getServletContext().getRealPath(path);
        for (int i = 0;i<file.length;i++){
            String tmpFileName = fileFileName[i];
            File tmpFile = file[i];
            realPath = CommomUtils.createDirByHash(tmpFileName,realPath);
            realPaths.add(realPath);
            if (file !=null){
                File saveFile = new File(new File(realPath),tmpFileName);
                if (!saveFile.getParentFile().exists())
                    saveFile.getParentFile().mkdirs();
                FileUtils.copyFile(tmpFile, saveFile);
            }
        }
    }

    //    以response方式输出json
    public void renderJson(String json) throws IOException {
        getResponse().setContentType("application/json;charset=UTF-8");
        getResponse().getWriter().write(json);
    }

//    邮件发送
    public  void sendEmail(String verificationCode, String email) throws Exception{
        try {
            MimeMessage mailMessage = mailSender.createMimeMessage();
            MimeMessageHelper messageHelper = new MimeMessageHelper(mailMessage);
            messageHelper.setFrom(mailSender.getUsername());
            messageHelper.setTo(email);
            messageHelper.setSubject("好久不见，这是校缘验证码");
//            ？register="+register
            String tits = "验证码将在一个小时候失效";
            tits = new String(tits.getBytes("iso-8859-1"),"utf-8");
            messageHelper.setText("<html><body>"+verificationCode+"</body></html>", true);
            Properties properties = new Properties();
            properties.put("mail.smtp.auth", "true");
            properties.put("mail.smtp.timeout", "25000");
            mailSender.send(mailMessage);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public ServletResponse getResponse(){
        return ServletActionContext.getResponse();
    }

    @Override
    public T getModel() {
        return model;
    }

    @Override
    public void setSession(Map<String, Object> session) {
        this.session = session;
    }

    public Integer getPageNo() {
        return pageNo;
    }

    public void setPageNo(Integer pageNo) {
        this.pageNo = pageNo;
    }

    public Integer getTotalCount() {
        return totalCount;
    }

    public void setTotalCount(Integer totalCount) {
        this.totalCount = totalCount;
    }

    public Integer getPageSize() {
        return pageSize;
    }

    public void setPageSize(Integer pageSize) {
        this.pageSize = pageSize;
    }

    public String getResult() {
        return result;
    }

    public void setResult(String result) {
        this.result = result;
    }

    public File[] getFile() {
        return file;
    }

    public void setFile(File[] file) {
        this.file = file;
    }

    public String[] getFileFileName() {
        return fileFileName;
    }

    public void setFileFileName(String[] fileFileName) {
        String[] tmpFileNames = new String[fileFileName.length];
        String tmpFileName = null;
        if (fileFileName.length>0){
            for (int i = 0; i < fileFileName.length;i++){
                tmpFileName = CommomUtils.createUUIDName(fileFileName[i]);
                tmpFileNames[i] = tmpFileName;
            }
        }
        this.fileFileName = tmpFileNames;
    }

    public String[] getFileContentType() {
        return fileContentType;
    }

    public void setFileContentType(String[] fileContentType) {
        this.fileContentType = fileContentType;
    }

    public String getRefreshNum() {
        return refreshNum;
    }

    public void setRefreshNum(String refreshNum) {
        this.refreshNum = refreshNum;
    }
}